<template>
  <el-container class="image-container">
    <el-header class="d-flex align-items-center">
      <div class="d-flex mr-auto">
        <el-select class="mr-2" v-model="searchForm.sort" style="width: 180px" size="small" placeholder="请选者图片排序方式">
          <el-option label="区域一" value="shanghai"></el-option>
          <el-option label="区域二" value="beijing"></el-option>
        </el-select>
        <el-input v-model="searchForm.keyWord" placeholder="请输入相册名称" class="mr-2" style="width: 200px" clearable size="small"></el-input>
        <el-button size="small" type="primary">搜索</el-button>
      </div>
      <template v-if="checkedImageList.length">
        <el-button type="danger" size="small" @click="delImage({all: true})">批量删除</el-button>
        <el-button type="warining" size="small" @click="unChoose">取消选中</el-button>
      </template>
      <el-button size="small" type="success" @click="openAlbumModel(false)">创建相册</el-button>
      <el-button @click="uploadModelFlag = true" size="small" type="warning">上传图片</el-button>
    </el-header>
    <el-container style="position: relative;">
      <el-aside class="bg-white border-right" width="200px" style="position: absolute; top: 0;bottom: 0;left: 0;">
        <ul class="list-group list-group-flush">
          <album-item 
            :active="albumIndex === index" 
            v-for="(item, index) in albums" 
            :key="index" 
            :index="index" 
            :item="item" 
            @albumChange="albumChange" 
            @openAlbumModel="openAlbumModel" 
            @albumDel="albumDel"></album-item>
        </ul>
      </el-aside>
      <el-container>
        <!-- 右侧主内容 -->
        <el-main style="position: absolute; top: 0; bottom: 0; left: 200px; right: 0;">
          <el-row :gutter="15">
            <el-col v-for="(item, index) in iamgeList" :key="index" :span="24" :lg="4" :md="6" :sm="8" :xs="12">
              <div 
                class="border card-wrapper mb-3"
                :class="{'border-danger' : item.isCheck}">
                <span v-show="item.isCheck" class="badge badge-danger">{{item.checkOrder}}</span>
                <el-card 
                  :body-style="{padding: 0}" 
                  shadow="hover" 
                  style="cursor: pointer;">
                  <img @click="chooseImage(item)" style="object-fit: cover; width: 100%; height: 150px;" :src="item.url" alt="">
                  <div class="imgwrapper">{{item.name}}</div>
                  <div class="p-2 text-center">
                    <el-button-group>
                      <el-button class="p-2" size="mini" icon="el-icon-view" @click="perviewImage(item.url)"></el-button>
                      <el-button class="p-2" size="mini" icon="el-icon-edit" @click="editImageName(item, index)"></el-button>
                      <el-button class="p-2" size="mini" icon="el-icon-delete" @click="delImage({index})"></el-button>
                    </el-button-group>
                  </div>
                </el-card>
              </div>
            </el-col>
          </el-row>

        </el-main>
      </el-container>
    </el-container>
    <el-footer class="d-flex border-top align-items-center px-0">
      <div style="width: 200px;" class="h-100 d-flex align-items-center justify-content-center border-right flex-shrink-0">
        <el-button-group>
          <el-button size="small" icon="el-icon-arrow-left">上一页</el-button>
          <el-button size="small">下一页<i class="el-icon-arrow-right el-icon--right"></i></el-button>
        </el-button-group>
      </div>
      <div style="flex: 1;" class="px-2">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[100, 200, 300, 400]"
          :page-size="100"
          layout="total, sizes, prev, pager, next, jumper"
          :total="400">
        </el-pagination>
      </div>
    </el-footer>


    <!-- 修改与添加相册 -->
    <el-dialog
      :title="computedAlbumModelTiele"
      :visible.sync="albumModel">
      <el-form ref="form" :model="albumForm" label-width="80px">
        <el-form-item label="相册名称">
          <el-input placeholder="请输入相册名称" v-model="albumForm.name" size="medium"></el-input>
        </el-form-item>
        <el-form-item label="">
          <el-input-number v-model="albumForm.sort" :min="0" size="medium"></el-input-number>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="medium" @click="albumModel = false">取 消</el-button>
        <el-button size="medium" type="primary" @click="confirmAlbumModel">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 上传图片弹窗 -->
    <el-dialog
      title="上传图片"
      :visible.sync="uploadModelFlag">
      <div class="text-center">
        <el-upload
          class="upload-demo"
          drag
          action="https://jsonplaceholder.typicode.com/posts/"
          multiple>
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="medium" @click="uploadModelFlag = false">取 消</el-button>
        <el-button size="medium" type="primary" @click="confirmAlbumModel">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 图片预览展示 -->
    <el-image-viewer 
      v-if="preViewImageModelFlag" 
      :on-close="closeViewer" 
      :url-list="[prevImageUrl]" />


  </el-container>
</template>

<script>
import albumItem from '@/components/image/album-item.vue'
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
const imgUrl = 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1567679013191&di=f48f3089c430e597bb108cd41128a890&imgtype=0&src=http%3A%2F%2Fpic1.win4000.com%2Fwallpaper%2F2018-05-30%2F5b0e44a6c4705.jpg'

export default {
  components: {albumItem, ElImageViewer},
  data() {
    return {
      searchForm: {
        sort: '',
        keyWord: ''
      },
      albums: [],
      // 左侧相册 默认编辑的索引 使用这个变量确定是新增 还是编辑
      albumsEidtIndex: -1,
      albumIndex: 0,
      albumModel: false,
      albumForm: {
        name: '',
        sort: 0
      },
      // 上传图片
      uploadModelFlag: false,
      // 图片模态框
      preViewImageModelFlag: false,
      // 查看图片的地址
      prevImageUrl: '',
      // 图片列表
      iamgeList: [],
      // 存储选中的图片的数据
      checkedImageList: [],
      currentPage: 1,

    }
  },
  created(){
    this._initSlide()
  },
  methods: {
    _initSlide(){
      for (let index = 0; index < 20; index++) {
        this.albums.push({
          name: '相册'+(index+1),
          num: Math.floor(Math.random()*(99-1)+1), // 1-99之间
          sort: Math.floor(Math.random()*(99-1)+1)
        })
        this.iamgeList.push({url: imgUrl, name: '朴敏英'+(index+1), isCheck: false, id: index, checkOrder: 0})
      }
    },
    // 点击左侧相册
    albumChange(index){
      this.albumIndex = index
    },
    // 删除左侧分类相册
    albumDel(index){
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.albums.splice(index, 1)
        this.$notify({
          type: 'success',
          title: '提示',
          message: '删除成功',
          duration: 3000
        })
      })
    },
    // 修改与创建 相册
    openAlbumModel(obj){
      // 修改
      if(obj){ // 赋值
        let {item, index} = obj
        // 初始化表单
        this.albumForm.name = item.name
        this.albumForm.sort = item.sort
        this.albumsEidtIndex = index
        // 打开窗口
        this.albumModel = true
        return
      }
      // 初始化
      this.albumsEidtIndex = -1
      this.albumForm = {name: '', sort: 0}
      this.albumModel = true
    },
    // 修改与创建相册 确定事件
    confirmAlbumModel(){
      // 判断是否是修改还是新增
      if(this.albumsEidtIndex > -1){ // 修改
        this.albumModel = false
        this._albumEdit()
      }else{ // 新增
        let {name, sort} = this.albumForm
        this.albums.unshift({
          name,
          sort,
          num: sort
        })
        this.albumModel = false
        this.$notify({
          type: 'success',
          title: '提示',
          message: '创建成功',
          duration: 3000
        })
      }
    },
    // 更新左侧相册修改后的数据
    _albumEdit(){
      let {name, sort} = this.albumForm
      this.albums[this.albumsEidtIndex].name = name
      this.albums[this.albumsEidtIndex].sort = sort
      this.$notify({
        type: 'success',
        title: '提示',
        message: '修改成功',
        duration: 3000
      })
    },
    // 预览图片
    perviewImage(imgUrl){
      this.preViewImageModelFlag = true
      this.prevImageUrl = imgUrl
    },
    // 关闭显示的预览图片
    closeViewer(){
      this.preViewImageModelFlag = false
    },
    // 修改图片名称
    editImageName(item, index){
      this.$prompt('请输入新的名称', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        // 弹窗初始值
        inputValue: item.name,
        inputValidator(val){
          if(val === '') return '图片名称不能为空'
        }
      }).then(({ value }) => {
        item.name = value
        this.$notify({
          type: 'success',
          title: '提示',
          message: '修改成功',
          duration: 3000
        })
      })
    },
    // 删除图片
    delImage(obj){
      this.$confirm(obj.all ? '是否删除选中图片?' : '是否删除该图片?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if(obj.all){ // 代表批量删除操作
          this._imageDelAll()
        }else{
          this.iamgeList.splice(obj.index, 1)
        }
        this.$notify({ 
          type: 'success',
          title: '提示',
          message: '删除成功',
          duration: 3000
        })
      })
    },
    // 批量删除
    _imageDelAll(){
      // 过滤掉 选中的数据 留下没选中的
      let list = this.iamgeList.filter(v =>{
        return !this.checkedImageList.some(c => c.id === v.id)
      })
      this.iamgeList = list
      this.checkedImageList = []
    },
    chooseImage(item){
      if(!item.isCheck){
        // 选中
        this.checkedImageList.push({id: item.id, url: item.url})
        // 计算选中的序号
        item.checkOrder = this.checkedImageList.length
        item.isCheck = true
      }else{
        // 取消选中 找到checkedImageList中的索引 进行删除 修改状态 重置数码
        let i = this.checkedImageList.findIndex(v => item.id === v.id)
        if(i === -1) return;
        // 重新计算序号
        let len = this.checkedImageList.length
        if(i+1 < len){ // 删除中间的某一个 特殊处理
          for(let j = i; j < len; j++){ // 只处理 点击项后面的
            let _index = this.iamgeList.findIndex(v => v.id === this.checkedImageList[j].id)
            if(_index !== -1){
              // 当前数值删除 后面的排序需要在原来的基础上减一即可
              this.iamgeList[_index].checkOrder--
            }
          }
        }
        // 如果选中的是最后一个 不需要计算
        this.checkedImageList.splice(i, 1);
        item.checkOrder = 0
        item.isCheck = false
      }
    },
    // 取消选中
    unChoose(){
      this.iamgeList.forEach(item=> {
        // 找到当前选中的索引 在原始数据中的位置 把选中态取消掉
        let i = this.checkedImageList.findIndex(v=> item.id === v.id)
        if(i > -1){
          item.isCheck = false
          item.checkOrder = 0
          this.checkedImageList.splice(i, 1) // 在存储选中的列表中删除
        }
      })
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
    }
  },
  computed: {
    // 处理相册弹窗显示的标题
    computedAlbumModelTiele(){
      return this.albumsEidtIndex > -1 ? '修改相册' : '创建相册'
    }
  }
}
</script>

<style scoped lang="less">
  .image-container{
    position: absolute;
    top: 55px;
    left: 0;
    right: 0;
    bottom: 0;
  }
  .imgwrapper{
    background: rgba(0,0,0,.5);
    width: 100%;
    color: #fff;
    margin-top: -30px;
    line-height: 30px;
    position: relative;
    font-size: 12px;
    padding-left: 10px;
  }
  .image-container /deep/ .el-icon-circle-close{
    color: #fff;
  }
  .card-wrapper{
    border-radius: 5px; 
    position: relative; 
    box-sizing: border-box;
  }
  .card-wrapper.border{
    border-color: transparent !important;
    &.border-danger{
      border-color: #dc3545!important;
    }
    .badge{
      position: absolute;right: 0; top: 0; font-size: 14px; font-weight: 400;
    }
  }
</style>